package com.gs.SynPatrolRep.fragment;

import android.content.Intent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.gs.SynPatrolRep.R;
import com.gs.SynPatrolRep.apiresult.ApiResultData;
import com.gs.SynPatrolRep.constant.AllConstants;
import com.gs.SynPatrolRep.constant.EventCode;
import com.gs.SynPatrolRep.db.bean.Event;
import com.gs.SynPatrolRep.db.dto.ShortDto;
import com.gs.SynPatrolRep.db.dto.VersionDto;
import com.gs.SynPatrolRep.dialog.CommDialogUtils;
import com.gs.SynPatrolRep.dialog.LanguageDialog;
import com.gs.SynPatrolRep.dialog.LoadingDialogUtils;
import com.gs.SynPatrolRep.dialog.ShortDialog;
import com.gs.SynPatrolRep.fragment.base.BaseFragment;
import com.gs.SynPatrolRep.presenter.SettingsPresenter;
import com.gs.SynPatrolRep.service.SignalRService;
import com.gs.SynPatrolRep.util.ActivityUtil;
import com.gs.SynPatrolRep.util.AppUtil;
import com.gs.SynPatrolRep.util.LanguageUtils;
import com.gs.SynPatrolRep.util.NotificationUtil;
import com.gs.SynPatrolRep.util.SPUtil;
import com.gs.SynPatrolRep.view.ISettingsView;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.List;
import java.util.Locale;

public class SettingsFragment extends BaseFragment<ISettingsView, SettingsPresenter> implements ISettingsView {

    private TextView tvLanguage, tvArea, tvVersion;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_settings;
    }

    @Override
    protected SettingsPresenter createPresenter() {
        return new SettingsPresenter();
    }

    @Override
    protected void initView() {
        OnClickListener onClickListener = new OnClickListener();
//        語言
        tvLanguage = fd(R.id.tv_language);
        tvLanguage.setOnClickListener(onClickListener);
//        場地
        tvArea = fd(R.id.tv_area);
        tvArea.setOnClickListener(onClickListener);
//        版本
        tvVersion = fd(R.id.tv_version);
        tvVersion.setText(AppUtil.getInstance().getVersion());
        fd(R.id.ll_version).setOnClickListener(onClickListener);
        fd(R.id.btn_signout).setOnClickListener(onClickListener);
    }

    @Override
    protected void initData() {
        tvLanguage.setText(LanguageUtils.getInstance().getStrLanguage());
        tvArea.setText(SPUtil.getInstance().getString(AllConstants.AREA_NAME));
    }

    @Override
    public void onGetAreaSuccess(ApiResultData<List<ShortDto>> apiResultData) {
        if (apiResultData.getStatus() != 2000) {
            Toast.makeText(context, apiResultData.getMessage(), Toast.LENGTH_LONG).show();
            return;
        }
        new ShortDialog(context, apiResultData.getData(), R.string.area,
                SPUtil.getInstance().getString(AllConstants.AREA_ID),
                new ShortDialog.IChoiceListener() {
                    @Override
                    public void getChoiceFromDialog(ShortDto bean) {
                        mPresenter.changeArea(bean.getName(), bean.getId());
                    }
                }).show();
    }

    @Override
    public void onGetAreaFail(Exception e) {
        Toast.makeText(context, R.string.network_error, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onUploadSiteSuccess(ApiResultData<String> apiResultData, String siteName, String siteId) {
        if (apiResultData.getStatus() != 2000) {
            Toast.makeText(context, apiResultData.getMessage(), Toast.LENGTH_LONG).show();
            return;
        }
        SPUtil.getInstance().putString(AllConstants.AREA_ID, siteId);
        SPUtil.getInstance().putString(AllConstants.AREA_NAME, siteName);
        EventBus.getDefault().post(new Event(EventCode.EVENT_SITE));
    }

    @Override
    public void onUploadSiteFail(Exception e) {
        Toast.makeText(context, R.string.network_error, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onUploadLanguageSuccess(ApiResultData<String> apiResultData, int languageId, Locale locale) {
        if (apiResultData.getStatus() != 2000) {
            Toast.makeText(context, apiResultData.getMessage(), Toast.LENGTH_LONG).show();
            return;
        }
        SPUtil.getInstance().putInt(AllConstants.LANGUAGE, languageId);
        LanguageUtils.getInstance().change(locale);
        EventBus.getDefault().post(new Event(EventCode.EVENT_LANGUAGE));
    }

    @Override
    public void onUploadLanguageFail(Exception e) {
        Toast.makeText(context, R.string.network_error, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onGetVersionSuccess(final ApiResultData<VersionDto> apiResultData) {
        if (apiResultData.getStatus() == 2000) {
            if (apiResultData.getData() != null) {
                int newVersion;
                int myVersion;
                try {
                    newVersion = Integer.parseInt(apiResultData.getData().getVersion().replace(".", ""));
                    myVersion = Integer.parseInt(AppUtil.getInstance().getVersion().replace(".", ""));
                } catch (NumberFormatException e) {
                    Toast.makeText(context, R.string.version_error, Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                    return;
                }
                if (newVersion > myVersion) {
                    CommDialogUtils.showDialog(context, getString(R.string.new_version),
                            apiResultData.getData().getDesc(), R.string.download,
                            new CommDialogUtils.DialogClickListener() {
                                @Override
                                public void cancelClick() {

                                }

                                @Override
                                public void okClick() {
                                    String fileName = apiResultData.getData().getOutputFile();
                                    File file = new File(getActivity().getCacheDir(), fileName);
                                    // 已下載過安裝包
                                    if (AppUtil.getInstance().fileIsExists(file)) {
                                        AppUtil.getInstance().installApk(getActivity(), file);
                                    } else {
                                        // 展示進度條
                                        CommDialogUtils.showProgressDialog(context);
                                        mPresenter.downloadFile(fileName, file);
                                    }
                                }
                            });
                } else {
                    Toast.makeText(context, R.string.is_new_version, Toast.LENGTH_LONG).show();
                }
            } else {
                Toast.makeText(context, R.string.version_null, Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    public void onGetVersionFails(Exception e) {
        Toast.makeText(context, R.string.network_error, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onDownloadFileSuccess(File file) {
        AppUtil.getInstance().installApk(getActivity(), file);
        CommDialogUtils.dismissProDialog();
    }

    @Override
    public void onDownloadProgress(int progress) {
        CommDialogUtils.setProgress(progress);
    }

    @Override
    public void onDownloadFails(Exception e) {
        Toast.makeText(context, R.string.download_error, Toast.LENGTH_LONG).show();
        CommDialogUtils.dismissProDialog();
    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(context);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }

    class OnClickListener implements View.OnClickListener {

        @Override
        public void onClick(final View v) {
            switch (v.getId()) {
                case R.id.tv_language:
                    new LanguageDialog(context, new LanguageDialog.IDoneListener() {
                        @Override
                        public void getDoneFromDialog(int checkedId) {
                            if (checkedId == R.id.rb_chinese) {
                                mPresenter.changeLanguage(1, Locale.TAIWAN);
                            } else if (checkedId == R.id.rb_english) {
                                mPresenter.changeLanguage(2, Locale.ENGLISH);
                            }
                        }
                    }).show();
                    break;
                case R.id.tv_area:
                    mPresenter.getArea();
                    break;
                case R.id.ll_version:
                    mPresenter.getVersion();
                    break;
                case R.id.btn_signout:
                    NotificationUtil.getInstance().getNotificationManager().cancelAll();
                    context.stopService(new Intent(context, SignalRService.class));
                    ActivityUtil.getInstance().finishActivity();
                    break;
            }
        }
    }
}
